//
//  NewsDetailView.swift
//  maozzi-rss
//
//  Created by 帽子 on 2020/5/30.
//  Copyright © 2020 帽子. All rights reserved.
//	详情 view

import SwiftUI

struct NewsDetailView: View {
    var newsItem: NewsItem
    @EnvironmentObject var userData: UserData

    var body: some View {
        HtmlSafariView(url: URL(string: self.newsItem.link!)!)
            .onDisappear {
                // 从未读集合中删除
                var readList: [NewsItem] = LocalCacheUtil.getAll(filename: UserData.readCacheFileName) ?? Array<NewsItem>()
                if !readList.contains(self.newsItem) {
                    readList.append(self.newsItem)
                    if LocalCacheUtil.save(filename: UserData.readCacheFileName, value: readList) {
                        self.userData.newsData.remove(at: self.userData.newsData.firstIndex(of: self.newsItem)!)
                    }
                }
                // 添加到已读集合
                let recentList: [NewsItem] = (LocalCacheUtil.getAll(filename: UserData.recentCacheFileName) ?? Array<NewsItem>()) + [self.newsItem]
                if LocalCacheUtil.save(filename: UserData.recentCacheFileName, value: recentList) {
                    self.userData.recentData = recentList
                }
            }
    }
}

struct NewsDetailView_Previews: PreviewProvider {
    static var previews: some View {
        NewsDetailView(newsItem: RSSUtil.get()[0])
    }
}
